package com.app.micaihu.view.army.fragment

import android.animation.Animator
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.FrameLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.app.base.BaseMvpFragment
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.base.BaseOldActivity
import com.app.micaihu.configure.ActivityRequestCode
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.LoadType
import com.app.micaihu.configure.UmEventId
import com.app.micaihu.utils.InteractiveUtils
import com.app.micaihu.utils.MobclickAgentUtils
import com.app.micaihu.utils.StatServiceUtils
import com.app.micaihu.view.army.activity.ArmyMedalListActivity
import com.app.micaihu.view.army.adapter.JoinedArmyListAdapter
import com.app.micaihu.view.army.contract.ArmyJoinedContract
import com.app.micaihu.view.army.header.JoinedArmyHeader
import com.app.micaihu.view.army.presenter.ArmyJoinedPresenter
import com.app.micaihu.view.bean.QuestionList
import com.app.micaihu.view.main.topic.PostDetailActivity
import com.app.micaihu.view.main.topic.PostSendActivity
import com.app.micaihu.view.main.view.WrapContentLinearLayoutManager
import com.app.micaihu.view.newsdetail.ImageShowActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.ViewUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.army_joined_list_fragment.*
import kotlinx.android.synthetic.main.army_joined_list_fragment.ivTopic
import kotlinx.android.synthetic.main.fragment_public_list.*
import kotlinx.android.synthetic.main.main_arms_list.refreshLayout

/**
 * 已加入军团
 */
class JoinedArmyListFragment : BaseMvpFragment<ArmyJoinedContract.View, ArmyJoinedPresenter>(), ArmyJoinedContract.View {

    override fun getLayoutId() = R.layout.army_joined_list_fragment
    override fun getPresenter() = ArmyJoinedPresenter()
    var isRecycleViewScroll = false
    var isTop = false
    var isBottom = false
    var isAnimatorEnd = false
    private var gid = ""
    private val joinedArmyListAdapter: JoinedArmyListAdapter by lazy {
        val joinedArmyListAdapter = JoinedArmyListAdapter()
        rvList.layoutManager = WrapContentLinearLayoutManager(context)
        headerView?.let { joinedArmyListAdapter.addHeaderView(it) }
        joinedArmyListAdapter.headerWithEmptyEnable = true
        joinedArmyListAdapter
    }
    private val headerView by lazy {
        context?.let { JoinedArmyHeader(it) }
    }

    override fun setData() {
        refreshLayout.setEnableLoadMore(true)
        refreshLayout.setEnableAutoLoadMore(true)
        rvList.adapter = joinedArmyListAdapter
        rvList.addOnScrollListener(MyScrollListener())
        LiveEventBus.get(Config.EventBus.armyTopicSuccess, Boolean::class.java).observe(this, Observer {
            ViewUtils.runOnUiThreadDelayed({
                refreshList()
            }, 200)
        })
        LiveEventBus.get(Config.EventBus.armyEditNoticeSuccess, Boolean::class.java).observe(this, Observer {
            ViewUtils.runOnUiThreadDelayed({
                refreshList()
            }, 200)
        })
        LiveEventBus.get(Config.EventBus.armyUpgradeSuccess, Boolean::class.java).observe(this, Observer {
            ViewUtils.runOnUiThreadDelayed({
                refreshList()
            }, 200)
        })
    }

    override fun lazyLoad() {
        joinedArmyListAdapter.setEmptyView(loadingView)
        mPresenter?.refresh()
    }

    override fun addListeners() {
        joinedArmyListAdapter.addChildClickViewIds(R.id.flLand, R.id.flComment, R.id.ivBigThumb, R.id.ivThumb0, R.id.ivThumb1, R.id.ivThumb2, R.id.ivHonourPic)
        joinedArmyListAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.flLand -> {
                    StatServiceUtils.event(Config.EventBauduId.teamlist_like, "军团_帖子列表点赞")
                    InteractiveUtils.getInstance().laud((view as FrameLayout?)!!, null)
                }
                R.id.flComment -> {
                    StatServiceUtils.event(Config.EventBauduId.teamlist_comment, "军团_帖子列表评论")
                    val item = joinedArmyListAdapter.getItem(position)
                    val intent = Intent(context, PostDetailActivity::class.java)
                    intent.putExtra(Config.Extra.PARAMETER1, item.id)
                    intent.putExtra(PostDetailActivity.COMMENT_SUM, item.replyNum)
                    intent.putExtra(PostDetailActivity.PARISE_SUM, item.praiseNum)
                    startActivityForResult(intent, ActivityRequestCode.REQUEST_CODE_TOPIC_DETAIL)
                    activity?.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain)
                }
                R.id.ivBigThumb,
                R.id.ivThumb0 -> {
                    val item = joinedArmyListAdapter.getItem(position)
                    showImageDetail(item.imgList, 0)
                }
                R.id.ivThumb1 -> {
                    val item = joinedArmyListAdapter.getItem(position)
                    showImageDetail(item.imgList, 1)
                }
                R.id.ivThumb2 -> {
                    val item = joinedArmyListAdapter.getItem(position)
                    showImageDetail(item.imgList, 2)
                }
                R.id.ivHonourPic -> {
                    val item = joinedArmyListAdapter.getItem(position)
                    val bundle = Bundle()
                    bundle.putString(Config.Extra.toUid, item.uid)
                    enterPager(ArmyMedalListActivity::class.java, bundle)
                }
            }
        }
        refreshLayout.setOnRefreshListener {
            // 这里的作用是防止下拉刷新的时候还可以上拉加载
            joinedArmyListAdapter.loadMoreModule.isEnableLoadMore = false
            mPresenter?.refresh()
        }
        refreshLayout.setOnLoadMoreListener {
            mPresenter?.loadMore()
        }
        joinedArmyListAdapter.setOnItemClickListener { adapter, view, position ->
            StatServiceUtils.event(Config.EventBauduId.teamlist_click, "军团_帖子列表点击")
            MobclickAgentUtils.event(UmEventId.topiclist_click, "军团")
            val item = joinedArmyListAdapter.getItem(position)
            val intent = Intent(context, PostDetailActivity::class.java)
            intent.putExtra(Config.Extra.PARAMETER1, item.id)
            intent.putExtra(Config.Extra.eventValue, "军团")
            intent.putExtra(PostDetailActivity.COMMENT_SUM, item.replyNum)
            intent.putExtra(PostDetailActivity.PARISE_SUM, item.praiseNum)
            startActivityForResult(intent, ActivityRequestCode.REQUEST_CODE_TOPIC_DETAIL)
            activity?.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain)
        }

        ivTopic.setOnClickListener {
            StatServiceUtils.event(Config.EventBauduId.team_post, "军团_发帖")
            val intent = Intent(context, PostSendActivity::class.java)
            val bundle = Bundle()
            bundle.putString(Config.Extra.id, gid)
            intent.putExtras(bundle)
            ActivityUtils.startActivity(intent)
        }
    }

    /**
     * 展示大图
     * @param imgList
     * @param i
     */
    private fun showImageDetail(imgList: ArrayList<String>, i: Int) {
        val intent = Intent(context, ImageShowActivity::class.java)
        intent.putStringArrayListExtra(Config.Extra.PARAMETER1, imgList)
        intent.putExtra(Config.Extra.PARAMETER2, i)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
        activity?.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain)
    }

    fun refreshList() {
        mPresenter?.refresh()
        rvList?.let {
            rvList.smoothScrollToPosition(0)
        }

    }

    override fun handleArmyList(result: BaseBean<QuestionList?>?, loadType: Int) {
        refreshLayout.finishRefresh(Config.delayRefresh)
        if (result == null) {
            if (joinedArmyListAdapter.data.isNotEmpty()) {
                if (LoadType.TYPE_REFRESH_ERROR == loadType) {
                    ToastUtils.showShort(R.string.empty_network_error)
                } else {
                    refreshLayout.finishLoadMore(false)
                }
            } else {
                if (LoadType.TYPE_REFRESH_ERROR == loadType) {
                    joinedArmyListAdapter.setEmptyView(errorView)
                } else {
                    joinedArmyListAdapter.setEmptyView(getEmptyView())
                }
            }
        } else {
            if (result.isSuccess()) {
                result.data?.let { data ->
                    if (LoadType.TYPE_REFRESH_SUCCESS == loadType) {
                        data.armyGroupInfo?.let {
                            gid = it.id
                            headerView?.setHeaderData(it)
                        }
                        headerView?.setArmyUpgrade(data.armyGroupUpgradeStatus)
                        headerView?.setSignData(data.mission?.signIn)
                        headerView?.setTaskData(data.mission?.missionList)
                        joinedArmyListAdapter.setList(data.cmtList)
                    } else if (LoadType.TYPE_LOAD_MORE_SUCCESS == loadType) {
                        joinedArmyListAdapter.addData(data.cmtList)
                    }
                    if (data.cmtList.isNullOrEmpty()) {
                        joinedArmyListAdapter.setEmptyView(getEmptyView(emptyText = "快来发第一篇军团帖子", height = 300f))
                        refreshLayout.finishLoadMoreWithNoMoreData()
                    } else {
                        refreshLayout.finishLoadMore(Config.delayLoadMore)
                    }
                    headerView?.setHeaderLine(joinedArmyListAdapter.data.isEmpty())
                }
            } else {
                ToastUtils.showShort(result.msg)
            }
        }

    }

    private inner class MyScrollListener : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            when (newState) {
                RecyclerView.SCROLL_STATE_IDLE -> {
                    isRecycleViewScroll = false
                    showShareImage()
                }
                RecyclerView.SCROLL_STATE_DRAGGING, RecyclerView.SCROLL_STATE_SETTLING ->
                    if (!isRecycleViewScroll && !isBottom && !isTop) {
                        isRecycleViewScroll = true
                        hideShareImage()
                    }
            }
        }

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            val bottom = recyclerView.canScrollVertically(1)
            val top = recyclerView.canScrollVertically(-1)
            isBottom = !bottom
            isTop = !top
        }
    }

    @SuppressLint("ObjectAnimatorBinding")
    private fun showShareImage() {
        val animator = ObjectAnimator.ofFloat(ivTopic, "translationX", 0f)
        animator.duration = 600
        if (!isAnimatorEnd) {
            animator.startDelay = 1200
        }
        animator.start()
    }

    @SuppressLint("ObjectAnimatorBinding")
    private fun hideShareImage() {
        isAnimatorEnd = false
        val animator = ObjectAnimator.ofFloat(ivTopic, "translationX", SizeUtils.dp2px(70f).toFloat())
        animator.duration = 600
        animator.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {}
            override fun onAnimationEnd(animation: Animator) {
                isAnimatorEnd = true
            }

            override fun onAnimationCancel(animation: Animator) {}
            override fun onAnimationRepeat(animation: Animator) {}
        })
        animator.start()
    }

}